# -*- coding: utf-8 -*-
import json
import logging
import flask
from flask import Flask, request
import DbAccess
import Utils


app = Flask(__name__)


@app.route("/health")
def hello():
    return "I am good"


@app.route("/generate_short_url")
def generate_short_url():
    long_url = request.args.get("long_url")
    db_access = DbAccess()
    existed_url = db_access.get_short_url(long_url)
    if existed_url is None:
        short_url = Utils.generate_short_id()
        try:
            db_access.add_url_mapping(long_url, short_url)
            result = {
                "status": 201,
                "short_url": short_url,
                "long_url": long_url,
                "error_message": ""
            }
        except Exception as e:
            logging.error(
                "adding url mapping is failed {0}, {1}", long_url, short_url)
            result = {
                "status": 500,
                "short_url": short_url,
                "long_url": long_url,
                "error_message": str(e)
            }
    else:
        result = {
            "status": 200,
            "short_url": existed_url.short_url,
            "long_url": existed_url.long_url,
            "error_message": ""
        }

    return json.dumps(result)


@app.route("/query_long_url")
def query_long_url():
    short_url = request.args.get("short_url")
    db_access = DbAccess()
    existed_url = db_access.get_long_url(short_url)
    if existed_url is not None:
        result = {
            "status": 200,
            "short_url": existed_url.short_url,
            "long_url": existed_url.long_url,
            "error_message": ""
        }
    else:
        result = {
            "status": 500,
            "short_url": "",
            "long_url": "",
            "error_message": ""
        }

    return json.dumps(result)


@app.route("/<short_url>")
def redirect_to_long_url(short_url):
    db_access = DbAccess()
    existed_url = db_access.get_long_url(short_url)
    if existed_url is not None:
        flask.redirect()
    else:
        return "could not detected the original url"


if __name__ == '__main__':
    app.run()
